<?php
 
 //验证码类
class Dbh {
     private $db;
     public $dbh;
     public $where_str;
     public $limit_str;
     public $select_str;
     


    //构造方法
    public function __construct() {
        $link=include($_SERVER['DOCUMENT_ROOT']."/config/database.php");
        $dsn=$link['dbms'].":host=".$link['localhost'].";dbname=".$link['dbname'];
        try {
            $dbh = new PDO($dsn, $link['username'], $link['pwd']); //初始化一个PDO对象
        } catch (Exception $e) {
            die("数据库连接失败");
        }

        $this->db=$dbh;
        $this->dbh=$this->db;
    }
    //方法不存在代用
    public function __call($fun,$param="")
    {
        echo "调用".$fun."方法不存在，传递的参数".implode(',',$param);
    }

    //开始查询
    public function select($arr=array()){
        $colunm=$arr?"":"*";
        if($arr){
            foreach ($arr as $value) {
                $colunm.=",".$value;
            }
            $colunm=substr($colunm,1);
        }
        
        $dbh=new Dbh();
        $dbh->select_str="SELECT ".$colunm." FROM ".get_class($this).$this->where_str.$this->limit_str;
        return $dbh;
        //return $this->db->query("SELECT ".$colunm." FROM ".get_class($this).$this->where_str.$this->limit_str);
    }
    //查询条件
    public function where($where_arr=""){
        $str=" WHERE 1=1 ";
        if($where_arr){
            foreach ($where_arr as $value) {
                $str.=" AND ".$value[0]."=".$value[1];
            }
        }

        $dbh=new Dbh();
        $dbh->where_str=$str;
        $dbh->limit_str=$this->limit_str;
        return $dbh;
    }
    public function limit($limit_arr=""){
        $str="";
        if(is_array($limit_arr)){
            $str=" LIMIT ".$limit_arr[0].",".$limit_arr[1];
        }
        else{
            $str=" LIMIT ".$limit_arr;
        }
        $dbh=new Dbh();
        $dbh->where_str=$this->where_str;
        $dbh->limit_str=$str;
        return $dbh;
    }

    //结果处理
    public function fetch(){
        return $this->db->query($this->select_str)->fetch(PDO::FETCH_ASSOC);
    }
    public function fetchALL(){
        return $this->db->query($this->select_str)->fetchAll(PDO::FETCH_ASSOC);
    }
    public function fetchColumn(){
        return $this->db->query($this->select_str)->fetchColumn();
    }

    //错误处理
    // public function errorinfo(){
    //     return $this->db->errorinfo;
    // }

    //事务处理
    public function beginTransaction(){
        return $this->db->beginTransaction();
    }
    public function rollBack(){
        return $this->db->rollBack();
    }
    public function commit(){
        return $this->db->commit();
    }



    
}
